package StudyCode.summary.textfile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CountLettersWithBufferedReader {
	private char lookFor;
	private Path file;

	public static void main(String[] args) throws IOException {
		char lookFor = '.';
		Path file = Paths.get("e:/Copy/test1.txt");
		int count = new CountLettersWithBufferedReader(lookFor, file).count();
		System.out.format("File '%s' 有 %d letter '%c'.%n", file, count, lookFor);
	}

	CountLettersWithBufferedReader(char lookFor, Path file) {
		this.lookFor = lookFor;
		this.file = file;
	}

	public int count() throws IOException {
		int count = 0;
		try (InputStream in = Files.newInputStream(file);
		     BufferedReader reader = new BufferedReader(
				     new InputStreamReader(in))) {
			String line = null;
			while ((line = reader.readLine()) != null) {
				for (int i = 0; i < line.length(); i++) {
					if (lookFor == line.charAt(i)) {
						count++;
					}
				}
			}
		} catch (IOException x) {
			System.err.println(x);
		}
		return count;
	}

}
